<?php
/**
 * 后台管理员登录
 */
defined('BASEPATH') OR exit("No direct script access allowed");

class Login extends CI_Controller{


	//构造初始化函数
	public function __construct(){
		parent::__construct();

		//加载数据库
		$this->load->database();

		//加载admin模型
		$this->load->model('admin/Doctor_model','doctor');
		$this->load->model('admin/DoctorJ_model','doctorj');

		//加载表单验证规则
		$this->load->library('form_validation');

		//加载辅助函数—>验证码
		$this->load->helper('captcha');
		date_default_timezone_set("PRC");
	}

	public function index()
	{
		//echo site_url('Login/index');
		$this->load->view("doctor/Login.html");
	}

	public function login()
	{
		//设置验证规则
		$this->form_validation->set_rules('adminNameValue','用户名','required');
		$this->form_validation->set_rules('passwordValue','密码','required');

	    //先验证规则
		if($this->form_validation->run()==false){
			echo validation_errors();
			exit();
		}

		//这里清除一下所有的登陆信息
		// $this->session->unset_userdata('upId');
		// $this->session->unset_userdata('doctorName');
		// $this->session->unset_userdata('doctorId');
		// $this->session->sess_destroy();


		//验证验证码
		//1 获取POST过来的验证码
		 $captha=strtolower($this->input->post('cpathValue'));
		 $code=strtolower($this->session->userdata('code'));
		if($captha!= $code){//验证码正确，进行注册
			echo '验证码不正确';
			exit();
		}
		else { //规则通过才开始获取

			$adminNameValue=$this->input->post('adminNameValue',TRUE);
			$passwordValue=$this->input->post('passwordValue',TRUE);
		
			if ($this->doctor->cheAdminByNP($adminNameValue,$passwordValue)){
				//开始寻找doctor的id号
				$doctorInfo=$this->doctor->getOneByNP($adminNameValue,$passwordValue);

				//这里的id号不能再是这个表的id号，而是应该要j表的id号,这里应该用openid去寻找对应的j表的id号，
				//由于是测试版本，所以直接用openid是111111去查
				// $weichat=$this->doctorj->getOneByOpenid("oO9UCwb7G4f4oYQireJCmcHudHD8"); //$doctorInfo['weichat']
				// $this->session->set_userdata('doctorId',$weichat['id']);
				// $this->session->set_userdata('doctorName',$adminNameValue);
				if($doctorInfo['weichat']=="未绑定"){
					$this->session->set_userdata('upId',$doctorInfo['id']);  //要更新的ID
					$this->session->set_userdata('doctorName',$adminNameValue);
					echo 2;
					exit();
				}
				//用openid去寻找对应的id号
				$weichat=$this->doctorj->getOneByOpenid($doctorInfo['weichat']); 
				$this->session->set_userdata('doctorId',$weichat['id']);
				$this->session->set_userdata('doctorName',$adminNameValue);
				echo 1;
			}
			else{
				echo '用户名或密码错误';

			}
		}


		//1 获取POST过来的数据
		//$adminNameValue=$this->input->post('adminNameValue');
		//$passwordValue=$this->input->post('passwordValue');
		
	}

	public function bdweichat()
	{

	}


	/**
	 * 生成验证码
	 * @return [type] [description]
	 */
	public function code()
	{
		//调用函数生成验证码
		$vals = array(
				'word_length' => 4,
				'img_width' => '290',
				'img_height' => '30',
		);
		$code=create_captcha($vals);
		$this->session->set_userdata('code',$code);
	}

	//测试之用
	public function test()
	{
		$code=strtolower($this->session->userdata('code'));
		echo $code;
	}

}
